package com.tony.pmp.server.controller;

import com.google.common.collect.Maps;
import com.tony.pmp.common.response.BaseResponse;
import com.tony.pmp.common.response.StatusCode;
import com.tony.pmp.common.utils.Constant;
import com.tony.pmp.common.utils.PageUtil;
import com.tony.pmp.common.utils.ValidatorUtil;
import com.tony.pmp.model.entity.SysUserEntity;
import com.tony.pmp.server.annotation.LogAnnotation;
import com.tony.pmp.server.service.SysUserService;
import com.tony.pmp.server.shiro.ShiroUtil;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: SysUserController
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/13/20:49
 * @Description: 用户管理
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {

    @Autowired
    private SysUserService sysUserService;

    /**
    * @Description: currInfo 获取当前登录用户的详情
    * @Param: []
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/13 20:56
    */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public BaseResponse currInfo() {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        Map<String, Object> resMap = Maps.newHashMap();
        try {
            resMap.put("user",getUser());
        } catch (Exception e) {
            return new BaseResponse(StatusCode.Fail);
        }
        response.setData(resMap);
        return  response;
    }

    /**
    * @Description: updatePassword 修改登录密码
    * @Param: [password, newPassword]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/13 21:35
    */
    @LogAnnotation("修改登录密码")
    @RequestMapping("/password")
    public BaseResponse updatePassword(String password,String newPassword) {
        if (StringUtils.isBlank(password) || StringUtils.isBlank(newPassword)) {
            log.info(StatusCode.PasswordCanNotBlank.getMsg());
            return new BaseResponse(StatusCode.PasswordCanNotBlank);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            //真正的处理逻辑，先校验旧密码输入是否正确，再更新新的密码
            SysUserEntity entity = getUser();
            final String salt = entity.getSalt();
            String oldPwd = ShiroUtil.sha256(password, salt);
            if (!entity.getPassword().equals(oldPwd)) {
                log.info(StatusCode.OldPasswordNotMatch.getMsg());
                return new BaseResponse(StatusCode.OldPasswordNotMatch);
            }
            String newPwd = ShiroUtil.sha256(newPassword, salt);
            //更新密码
            log.info(">>>>>>密码正确，开始执行密码操作>>>>>>");
            log.info(">>>>>>密码更新结果：" + sysUserService.updatePassword(entity.getUserId(),oldPwd,newPwd));
        } catch (Exception e) {
            log.info(StatusCode.UpdatePasswordFail.getMsg());
            return new BaseResponse(StatusCode.UpdatePasswordFail);
        }
        return response;
    }

    /**
    * @Description: list 获取用户列表信息(分页)
    * @Param: [paramMap]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/26 11:10
    */
    @RequestMapping("/list")
    @RequiresPermissions(value = {"sys:user:list","sys:user:info"})
    public BaseResponse list(@RequestParam Map<String,Object> paramMap) {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        Map<String,Object> resMap = Maps.newHashMap();
        try {
            log.info("获取用户列表的信息为：{}",paramMap);
            PageUtil page = sysUserService.queryPage(paramMap);
            resMap.put("page",page);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        response.setData(resMap);
        return response;
    }

    /**
    * @Description: save 保存用户信息
    * @Param: [entity, result]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/26 14:19
    */
    @RequestMapping("/save")
    @RequiresPermissions(value = {"sys:user:save"})
    public BaseResponse save(@RequestBody @Validated SysUserEntity user, BindingResult result) {
        String res = ValidatorUtil.checkResult(result);
        if (StringUtils.isNotBlank(res)) {
            return new BaseResponse(StatusCode.InvalidParams.getCode(),res);
        }
        if (StringUtils.isBlank(user.getPassword())) {
            return new BaseResponse(StatusCode.PasswordCanNotBlank);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            log.info("新增用户的状态为：{}",sysUserService.saveUser(user));
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    /**
    * @Description: info 获取用户详情信息
    * @Param: [userId]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/26 17:13
    */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions(value = {"sys:user:info"})
    public BaseResponse info(@PathVariable Long userId) {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        Map<String,Object> resMap = Maps.newHashMap();
        try {
            log.info("用户的id为：{}",userId);
            resMap.put("user",sysUserService.getInfo(userId));
            response.setData(resMap);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    /**
    * @Description: update 更新用户信息
    * @Param: [user, result]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/26 21:40
    */
    @RequestMapping("/update")
    @RequiresPermissions(value = {"sys:user:update"})
    public BaseResponse update(@RequestBody @Validated SysUserEntity user,BindingResult result) {
        String res = ValidatorUtil.checkResult(result);
        if (StringUtils.isNotBlank(res)) {
            return new BaseResponse(StatusCode.InvalidParams,res);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            log.info("修改的用户信息为：{}",user);
            log.info("用户修改的状态为：{}",sysUserService.updateUser(user));
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    /**
    * @Description: delete 删除用户信息
    * @Param: [ids]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/27 11:21
    */
    @RequestMapping("/delete")
    @RequiresPermissions(value = {"sys:user:delete"})
    public BaseResponse delete(@RequestBody Long[] ids) {
        if (ids == null || ids.length <= 0) {
            return new BaseResponse(StatusCode.InvalidParams);
        }
        //超级管理员:admin不能删除
        if (ArrayUtils.contains(ids, Constant.SUPER_ADMIN)) {
            return new BaseResponse(StatusCode.SysUserCanNotBeDelete);
        }
        //当前用户不能删除
        if (ArrayUtils.contains(ids,getUserId())) {
            return new BaseResponse(StatusCode.CurrUserCanNotBeDelete);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            sysUserService.deleteUser(ids);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    /**
    * @Description: restPwd 重置密码
    * @Param: [ids]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/27 14:53
    */
    @RequestMapping("/psd/reset")
    @RequiresPermissions(value = {"sys:user:resetPwd"})
    public BaseResponse restPwd(@RequestBody Long[] ids) {
        if (ids == null || ids.length <= 0) {
            return new BaseResponse(StatusCode.InvalidParams);
        }
        //超级管理员：admin不能删除;当前用户不能删除
        if (ArrayUtils.contains(ids,Constant.SUPER_ADMIN) || ArrayUtils.contains(ids,getUserId())) {
            return new BaseResponse(StatusCode.SysUserAndCurrUserCanNotResetPsd);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            sysUserService.updatePwd(ids);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.UpdatePasswordFail);
        }
        return response;
    }
}
